<template>
  <basic-container>
    <avue-crud :option="customerInfo" :table-loading="loading" :data="data" v-model:page="page" v-model:search="search"
      :permission="permissionList" :before-open="beforeOpen" v-model="form" ref="crud" @sort-change="sortChange"
      @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel" @search-change="searchChange"
      @search-reset="searchReset" @selection-change="selectionChange" @current-change="currentChange"
      @size-change="sizeChange" @on-load="onLoad" @refresh-change="onLoad(page)">
      <!--v-model:defaults = "defaults"-->
      <template #menu-left>
        <el-button type="primary" icon="el-icon-plus" v-if="permission.customer_add" @click="handleAdd">新 增
        </el-button>
        <el-button type="danger" icon="el-icon-delete" v-if="permission.customer_delete" @click="handleDelete">删 除
        </el-button>
        <el-button type="warning" icon="el-icon-download" v-if="permission.customer_delete" @click="handleExport">导 出
        </el-button>
      </template>

      <template #creditLimit-search="{ disabled, size }">
        <div style="display: flex;flex-direction: start;">

          <el-select v-model="search.creditLimitRule" placeholder="比较" filterable clearable>
            <el-option label="" value=""></el-option>
            <el-option value=">" label="大于">大于 </el-option>
            <el-option value=">=" label="大于等于">大于等于 </el-option>
            <el-option value="=" label="等于">等于 </el-option>
            <el-option value="!=" label="不等于">不等于 </el-option>
            <el-option value="<=" label="小于等于">小于等于 </el-option>
            <el-option value="<" label="小于">小于 </el-option>
          </el-select>


          <el-input-number v-model="search.creditLimit" :min="0" :max="999999999999" precision="2"
            :controls="defaultControl" placeholder="信用额度" style="min-width: 180px;"></el-input-number>

        </div>
      </template>

      <template #createTime-search="{ disabled, size }">
        <!--<div style="display: flex;flex-direction: start;">-->
          <!--<el-select v-model="search.createTimeRule" placeholder="比较" filterable clearable>-->
            <!--<el-option label="" value=""></el-option>-->
            <!--<el-option value=">" label="大于">大于 </el-option>-->
            <!--<el-option value=">=" label="大于等于">大于等于 </el-option>-->
            <!--<el-option value="=" label="等于">等于 </el-option>-->
            <!--<el-option value="!=" label="不等于">不等于 </el-option>-->
            <!--<el-option value="<=" label="小于等于">小于等于 </el-option>-->
            <!--<el-option value="<" label="小于">小于 </el-option>-->
          <!--</el-select>-->
          <!--<el-date-picker size="default" v-model="search.createTimeSearch" type="date" :format="dateFormat"-->
            <!--:value-format="dateFormat" :unlink-panels="true" clearable placeholder="创建日期"-->
            <!--@change="handleDatePickerChange" :picker-options="pickerOptions">-->
          <!--</el-date-picker>-->
        <!--</div>-->
        <el-date-picker
                size="default"
                style="width:94%"
                v-model="this.createTimeRange"
                type="daterange"
                :format="dateFormat"
                :value-format="dateFormat"
                unlink-panels
                start-placeholder="Start Date"
                end-placeholder="End Date"
                clearable
                placeholder="创建日期"
                @change="handleDatePickerChange"
                :picker-options="pickerOptions"
        >
        </el-date-picker>
      </template>

      <template #menu="{ row, size, type }">
        <el-tooltip content="查看" placement="top">
          <el-button icon="el-icon-view" link :size="size" :type="type" @click="() => handleView(row)"
            v-if="permission.customer_view">
          </el-button>
        </el-tooltip>
        <el-tooltip content="修改" placement="top">
          <el-button icon="el-icon-edit" link :size="size" :type="type" @click="() => handleEdit(row)"
                     v-if="permission.customer_edit">
          </el-button>
        </el-tooltip>
        <el-tooltip content="产品审核" placement="top">
          <el-button icon="Stamp" link :size="size" :type="type" @click="() => showMaterialAudit(row)"
                     v-if="permission.customer_material_audit">
          </el-button>
        </el-tooltip>
        <el-tooltip content="删除" placement="top">
          <el-button icon="el-icon-delete" link :size="size" :type="type" @click="() => rowDel(row)"
            v-if="permission.customer_delete">
          </el-button>
        </el-tooltip>
      </template>
    </avue-crud>

    <CustomerDialogForm ref="dialogForm"  :title="title" @success="onLoad(page)"/>
    <CustomerDialogEdit  ref="dialogEdit" :title="title" @success="onLoad(page)"/>
    <material-audit ref="materialAudit" ></material-audit>

  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/anwise/customer/customer';
import { customerInfo } from '@/const/anwise/customer/customer';
import { mapGetters } from 'vuex';
import { getDictionary } from '@/api/system/dictbiz';
import { setStore, getStore } from '@/utils/store';
import $Mode from '@/mac/mode/index';
import website from '@/config/website';
import { getToken } from '@/utils/auth';
import { exportBlob } from '@/api/common';
import { downloadXls } from '@/utils/util';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import func from '@/utils/func';
import CustomerDialogForm from './customer_dialog_form.vue';
import CustomerDialogEdit from './customer_dialog_edit.vue';
import MaterialAudit from './components/material_audit.vue';
export default {
  components: {
    CustomerDialogForm,
    CustomerDialogEdit,
      MaterialAudit
  },
  data() {
    return {
      tableName: 'customer_table',
      defaults: {},
        createTimeRange:[],
      customerInfo: customerInfo,
      defaultControl: false,
      form: {},
      query: {},
      loading: true,
      data: [],
      selectionList: [],
      searchShow: true,
      searchMenuSpan: 6,
      dateFormat: 'YYYY-MM-DD',
      pickerOptions: {},
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
      },
      search: {},
      direction: 'rtl',
      customerId: 0,
      customerName: '安伟客户表',
      title:'',
      editable : ''
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.customer_add, false),
        viewBtn: this.validData(this.permission.customer_view, false),
        delBtn: this.validData(this.permission.customer_delete, false),
        editBtn: this.validData(this.permission.customer_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  mounted() {
    console.log(this.permission);
    // this.$nextTick(() =>{
    //     console.log(getStore({name: this.tableName }));
    //     this.defaults = getStore({name: this.tableName }) || {};
    //     console.log(this.defaults);
    //     this.$refs.crud.refreshTable();
    // })
    setTimeout(() => {
      this.customerInfo.searchShow = false;
    }, 500);
  },
  // unmounted() {
  //     setStore({name: this.tableName, content: this.defaults });
  // },
  methods: {
      showMaterialAudit(row) {
          this.$refs.materialAudit.show(row.id);
      },
    save(){
      this.$refs.dialogEdit.$refs.form.submit()
    },
    success(){
      console.log(34444)
     this.$refs.CustomerDialogEdit.handleClose()
    },
    initDict() {
      getDictionary({ code: 'customer_type' }).then(res => {
        this.customerTypeList = res.data.data;
      });
    },
    handleAdd() {
      this.title = '创建客户'
      this.$refs.dialogForm.init()
    },
    handleExport() {
      // const account = func.toStr(this.search.account);
      // const realName = func.toStr(this.search.realName);
      NProgress.start();
      exportBlob(
        `/blade-anwise/customer/customer/export?${this.website.tokenHeader
        }=${getToken()}`, this.search
      ).then(res => {
        downloadXls(res.data, `客户数据${this.$dayjs().format('YYYYMMDDHHmmss')}.xlsx`);
        NProgress.done();
      });
    },
    sortChange(val) {
      console.log(val)
      this.sort = {
        prop: val.prop,
        order: val.order
      };
      let order = "";
      if (this.sort.prop && this.sort.order) {
        if (this.sort.order === "descending") {
          order = `${this.sort.prop} desc`
        } else {
          order = `${this.sort.prop} asc`
        }
      }
      this.query.orderBy = order;
      this.onLoad(this.page);
    },
    onLoadBefore(page, params) {
      let order = "";
      if (this.sort.prop && this.sort.order) {
        if (this.sort.order === "descending") {
          order = `${this.sort.prop} desc`
        } else {
          order = `${this.sort.prop} asc`
        }
      }
      params.order = order;
      return false;
    },
    // 主表模块
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    // rowStyle() {
    //   return {
    //     height: '20px !important',
    //   };
    // },
    handleView(row) {
      this.title = '客户详情'
      this.customerId = row.id
      this.editable = false
      this.$refs.dialogEdit.init(this.customerId,this.editable)
    },
    handleEdit(row) {
      this.title = '编辑客户'
      this.customerId = row.id
      this.editable = true
      this.$refs.dialogEdit.init(this.customerId,this.editable)


    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
        this.createTimeRange = [];
        this.search.createTimeStart = '';
        this.search.createTimeEnd = '';
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
      handleDatePickerChange(value) {
          console.log(value);
          if (value) {
              this.search.createTimeStart = value[0];
              this.search.createTimeEnd = value[1];
          } else {
              this.search.createTimeStart = '';
              this.search.createTimeEnd = '';
          }
      },
  },
};
</script>
<style lang="scss" scoped></style>
